import java.util.Arrays;

public class KMP {
    /**
     * KMP字符串匹配算法
     */
    public static int kmp(String str, String par, int[] next) {//str文本串  par 模式串
        for (int i = 0, j = 0; i < str.length(); i++) {
            // 匹配失败回溯到next[j - 1]的位置
            while (j > 0 && str.charAt(i) != par.charAt(j)) {
                j = next[j - 1];
            }
            if (str.charAt(i) == par.charAt(j)) {
                j++;
            }
            if (j == par.length()) {
                return i - j + 1;
            }
        }
        return 0;
    }

    // next[i] 存放[0,i]中匹配的前后缀字符数
    public static int[] getNext(String par) {
        int[] next = new int[par.length()];
        for (int i = 1, j = 0; i < par.length(); i++) {
            while (j > 0 && par.charAt(j) != par.charAt(i)) {
                j = next[j - 1];
            }
            if (par.charAt(i) == par.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static void main(String[] args) {
        String str = "ssdfgasdbababa";
        String par = "ababaaaba";
        int[] next = getNext(par);
        System.out.println(Arrays.toString(next));
        int res = kmp(str, par, next);
        System.out.println(res);
    }
}
